import Const from "./const";
import Data from "./data";
import Util from "./util";

function Api() {
    function handlerError(body, showTip, reject) {
        if (showTip) {
            Util.showTip("", (body && body.message) || "数据获取失败")
        }

        return reject({
            code: body.code,
            message: body.message
        });
    }

    function request(method, url, params, showTip = true, contentType = "application/x-www-form-urlencoded") {
        let token = Data.getToken() || "";
        let host = Const.NET.END_POINT;
        return new Promise((resolve, reject) => {
            let requestData = "";

            if (method.startsWith("~")) {
                requestData = params;
            } else {
                if (!token) {
                    Util.showTip("", "请先登录, 再进行其他操作", () => {
                        Util.reLaunchGo("/pages/login/main")
                    })
                    return false;
                } else {
                    requestData = Object.assign({
                        token: token
                    }, params);
                }
            }

            method = method.replace("~", "");

            console.info(`${host}/${url}?${Util.transformObjectToUrlencodedData(requestData)}`);

            uni.request({
                url: `${host}/${url}`,
                data: requestData,
                method: method,
                header: {
                    "content-type": contentType
                },
                success(res) {
                    let body = res.data;
                    if (body.hasOwnProperty("code") && body.code === 0) {
                        return resolve(body.data)
                    }

                    if (body.hasOwnProperty("code") && body.code === Const.ERROR.ERROR_AUTH_FAIL) {
                        Data.clearAuthData()
                        Util.reLaunchGo("/pages/login/main")
                        return
                    }

                    handlerError(body, showTip, reject)
                },
                fail(reason) {
                    return reject({
                        code: Const.ERROR.ERROR_NETWORK,
                        message: reason
                    });
                }
            });
        });
    }

    return {
        Wx: {
            decrypt: (params) => {
                return request('~POST', 'wx/decrypt', params)
            },
            initConnect: () => {
                return request('~POST', 'wx/initConnect')
            },
        },
        Common: {
            sendSms: (params) => {
                return request('~POST', 'common/smsSend', params)
            }
        },
    }
}

export default new Api()
